﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;

namespace ChromeKillerApp
{
    public partial class MainWindow : Window
    {
        private DispatcherTimer timer;
        private int remainingSeconds;

        public MainWindow()
        {
            InitializeComponent();
            InitializeTimer();
        }

        private void InitializeTimer()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += Timer_Tick;
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            int minutes = 0;

            // 优先检查自定义时间
            if (!string.IsNullOrWhiteSpace(txtCustomTime.Text))
            {
                if (!int.TryParse(txtCustomTime.Text, out minutes) || minutes <= 0)
                {
                    MessageBox.Show("请输入有效的正整数作为分钟数。");
                    txtCustomTime.Focus();
                    return;
                }
            }
            else
            {
                // 使用下拉框选择的时间
                int selectedIndex = cmbTime.SelectedIndex;
                if (selectedIndex < 0) return;
                minutes = (selectedIndex + 1) * 20; // 20, 40, 60, 80
            }

            remainingSeconds = minutes * 60;
            txtStatus.Text = $"将在 {minutes} 分钟后关闭 Chrome...";
            btnStart.IsEnabled = false;

            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            remainingSeconds--;

            if (remainingSeconds <= 0)
            {
                timer.Stop();
                KillChrome();
                txtStatus.Text = "Chrome 已关闭";
                btnStart.IsEnabled = true;
            }
            else
            {
                int mins = remainingSeconds / 60;
                int secs = remainingSeconds % 60;
                txtStatus.Text = $"剩余时间: {mins:D2}:{secs:D2}";
            }
        }

        private void KillChrome()
        {
            try
            {
                Process.Start("taskkill", "/f /im chrome.exe");
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法关闭 Chrome: " + ex.Message);
            }
        }

        // 只允许输入数字
        private void txtCustomTime_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !IsTextAllowed(e.Text);
        }

        private static bool IsTextAllowed(string text)
        {
            foreach (var c in text)
            {
                if (!char.IsDigit(c))
                    return false;
            }
            return true;
        }
    }
}